﻿using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate;
using NHibernate.Criterion;
using SinBiota.Model.Business.PersistenceServices.Interfaces;
using SinBiota.Model.Business.StatisticsServices.Interfaces;
using SinBiota.Model.Entities;
using SinBiota.Model.Exceptions;
using SinBiota.Model.Persistence.ComplexQueries.Interfaces;

namespace SinBiota.Model.Business.StatisticsServices.Implementation
{
    public class OccurrenceStatistics : IOccurrenceStatistics
    {
        private readonly IRepositoryStatistics _repositoryStatistics;


        public OccurrenceStatistics(IRepositoryStatistics repositoryStatistics, IOccurrencePersistenceServices occurrencePersistenceServices)
        {
            _repositoryStatistics = repositoryStatistics;
        }

        public int TotalOccurrences()
        {
            return _repositoryStatistics.TotalofEntity<Occurrence>();
        }


        public IDictionary<string, int> OccurrencesByMonthYear()
        {
            var monthYear = new Dictionary<string, int>();
            // group all occurrences by start date, then remove the day and create a new dictionary:
            foreach (var pair in _repositoryStatistics.CountEntityGroupByProperty<Occurrence, string>("StartDate").OrderBy(x => x.Key.Substring(6) + x.Key.Substring(3,5)))
            {
                var dateWithoutDay = pair.Key.Substring(3);
                if (!monthYear.Keys.Contains(dateWithoutDay)) monthYear[dateWithoutDay] = 0;
                monthYear[dateWithoutDay] += pair.Value;
            }
            return monthYear;
            
        }
    }
}